package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.result.R;
import com.atguigu.eduservice.entity.*;
import com.atguigu.eduservice.entity.frontvo.CourseQueryVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.entity.vo.CourseQuery;
import com.atguigu.eduservice.feign.VodFeignService;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.MyException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author kabuda
* @description 针对表【edu_course(课程)】的数据库操作Service实现
* @createDate 2023-04-24 14:04:24
*/
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse>
    implements EduCourseService{

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    private EduChapterService eduChapterService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodFeignService vodFeignService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveCourse(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        boolean save = this.save(eduCourse);
        if(!save){
            throw new MyException(20001,"课程添加失败");
        }

        EduCourseDescription description = new EduCourseDescription();
        //一对一主键共享
        description.setId(eduCourse.getId());
        description.setDescription(courseInfoVo.getDescription());
        boolean save1 = eduCourseDescriptionService.save(description);
        if(!save1){
            throw new MyException(20001,"课程详情添加失败");
        }
        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourse(String id) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        EduCourse course = this.getOne(wrapper);

        QueryWrapper<EduCourseDescription> wrapperDetail = new QueryWrapper<>();
        wrapperDetail.eq("id",id);
        EduCourseDescription description = eduCourseDescriptionService.getOne(wrapperDetail);

        CourseInfoVo courseInfoVo = new CourseInfoVo();
        if(description!=null){
            courseInfoVo.setDescription(description.getDescription());
        }
        if(course!=null){
            BeanUtils.copyProperties(course,courseInfoVo);
        }

        return courseInfoVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCourse(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        boolean b = this.updateById(eduCourse);
        if(!b){
            throw new MyException(2001,"更新课程失败");
        }

        EduCourseDescription description = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo,description);

        boolean b1 = eduCourseDescriptionService.updateById(description);
        if(!b1){
            throw new MyException(2001,"更新课程详情失败");
        }

    }

    @Override
    public CoursePublishVo courseInfo(String id) {
        CoursePublishVo coursePublishVo=this.baseMapper.courseInfo(id);
        return coursePublishVo;
    }

    @Override
    public R pageQuery(Long page, Long limit, CourseQuery courseQuery) {
        Page<EduCourse> coursePage = new Page<>(page,limit);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        String title = courseQuery.getTitle();
        String subjectId = courseQuery.getSubjectId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String teacherId = courseQuery.getTeacherId();

        wrapper.like(StringUtils.hasText(title),"title",title);
        wrapper.eq(StringUtils.hasText(subjectId),"subject_id",subjectId);
        wrapper.eq(StringUtils.hasText(subjectParentId),"subject_parent_id",subjectParentId);
        wrapper.eq(StringUtils.hasText(teacherId),"teacher_id",teacherId);


        IPage<EduCourse> courseIPage = this.page(coursePage, wrapper);
        return R.ok().data("rows",courseIPage.getRecords()).data("total",courseIPage.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeCourseInfo(String courseId) {
        //删除课程
        boolean b = this.removeById(courseId);
        if(!b){
            throw new MyException(20001,"删除课程失败");
        }
        //TODO 删除阿里云OSS封面

        //删除课程详情
        LambdaQueryWrapper<EduCourseDescription> descriptionWrapper = new LambdaQueryWrapper<>();
        descriptionWrapper.eq(EduCourseDescription::getId,courseId);
        eduCourseDescriptionService.remove(descriptionWrapper);
        //删除章节
        LambdaQueryWrapper<EduChapter> chapterWrapper = new LambdaQueryWrapper<>();
        chapterWrapper.eq(EduChapter::getCourseId,courseId);
        eduChapterService.remove(chapterWrapper);

        //删除小节
        LambdaQueryWrapper<EduVideo> eduVideoWrapper = new LambdaQueryWrapper<>();
        eduVideoWrapper.eq(EduVideo::getCourseId,courseId);
        //TODO 删除阿里云视频点播
        List<EduVideo> list = eduVideoService.list(eduVideoWrapper);
        for (EduVideo video : list){
            vodFeignService.delete(video.getVideoSourceId());
        }
        eduVideoService.remove(eduVideoWrapper);
    }
    /**
     * 观看量降序获取前八个课程
     * @return
     */
    @Cacheable(value = "banner",key = "'indexCourse'")
    @Override
    public List<EduCourse> indexCourse() {
        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(EduCourse::getViewCount);
        wrapper.last("limit 8");
        List<EduCourse> list = this.list(wrapper);
        return list;
    }

    @Override
    public Map<String, Object> searchList(Long page, Long limit, CourseQueryVo courseQueryVo) {
        Page<EduCourse> coursePage = new Page<EduCourse>(page, limit);
        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(StringUtils.hasText(courseQueryVo.getTeacherId()),EduCourse::getTeacherId,courseQueryVo.getTeacherId());
        wrapper.eq(StringUtils.hasText(courseQueryVo.getSubjectParentId()),EduCourse::getSubjectParentId,courseQueryVo.getSubjectParentId());
        wrapper.eq(StringUtils.hasText(courseQueryVo.getSubjectId()),EduCourse::getSubjectId,courseQueryVo.getSubjectId());
        wrapper.like(StringUtils.hasText(courseQueryVo.getTitle()),EduCourse::getTitle,courseQueryVo.getTitle());
        wrapper.orderByDesc(StringUtils.hasText(courseQueryVo.getPriceSort()),EduCourse::getPrice);
        wrapper.orderByDesc(StringUtils.hasText(courseQueryVo.getGmtCreateSort()),EduCourse::getGmtCreate);
        wrapper.orderByDesc(StringUtils.hasText(courseQueryVo.getBuyCountSort()),EduCourse::getBuyCount);

        baseMapper.selectPage(coursePage, wrapper);
        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        boolean hasNext = coursePage.hasNext();
        boolean hasPrevious = coursePage.hasPrevious();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return map;
    }

    @Override
    public CourseWebVo FrontCourseInfo(String courseId) {
        CourseWebVo courseWebVo=this.baseMapper.FrontCourseInfo(courseId);
        return courseWebVo;
    }

    @Override
    public void addViewCount(String courseId) {
        EduCourse course = this.getById(courseId);
        course.setViewCount(course.getViewCount()+1);
        this.updateById(course);
    }


}




